package com.rongke.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.model.*;
import com.rongke.service.*;
import com.rongke.web.apix.TongDunSDKAuth;
import com.rongke.web.apix.TongdunYYSAuth;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/api/tdSDK")
@Transactional
@CrossOrigin
public class TongDunSDKController {
    private Logger log = Logger.getLogger(this.getClass());
    /**
     * 同盾淘宝回调
     * @param notify_event
     * @param notify_type
     * @param notify_time
     * @param sign
     * @param notify_data
     */
    @Autowired
    private TbLogService tbLogService;
    @Autowired
    private TbBaseInfoService tbBaseInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private TbReceiverService tbReceiverService;
    @Autowired
    private TdGjjBaseInfoService tdGjjBaseInfoService;
    @Autowired
    private TdGjjBillRecordService tdGjjBillRecordService;
    @Autowired
    private TdGjjPayInfoService tdGjjPayInfoService;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private YYSLogService yysLogService;
    @Autowired
    private UserPhoneRecordService userPhoneRecordService;
    @RequestMapping(value = "/tdSDKCallBack", method = RequestMethod.POST)
    public void tdTbSDKCallBack(String notify_data,String passback_params,String notify_even){
        try{
            log.debug("回调入参："+notify_data);
            JSONObject notify_dataJO = JSON.parseObject(notify_data);
            String taskId = notify_dataJO.getString("task_id");
            String code1 = notify_dataJO.getString("code");
            JSONObject data = notify_dataJO.getJSONObject("data");
            if("0".equals(code1)){

                //淘宝
                if(data.getString("channel_type").equals("DS")&&data.getString("channel_code").equals("000003")){
                    JSONObject resultJO = TongDunSDKAuth.TongDunSDKQuery(taskId);
                    if(resultJO != null){
                        Integer code = resultJO.getInteger("code");
                        if(code == 0){
                            JSONObject dataJO = resultJO.getJSONObject("data");
                            if(dataJO != null){
                                JSONObject taskDataJO = dataJO.getJSONObject("task_data");
                                if(taskDataJO != null){
                                    TbLog tbLog = new TbLog();
                                    JSONObject baseInfoJO = taskDataJO.getJSONObject("base_info");
                                    if (baseInfoJO != null){
                                        EntityWrapper ew = new EntityWrapper();
                                        ew.eq("task_id",taskId);
                                        tbLog = tbLogService.selectOne(ew);
                                        TbBaseInfo tbBaseInfo = new TbBaseInfo();
                                        tbBaseInfo.setUserName(baseInfoJO.getString("user_name"));
                                        tbBaseInfo.setEmail(baseInfoJO.getString("email"));
                                        tbBaseInfo.setUserLevel(baseInfoJO.getString("user_level"));
                                        tbBaseInfo.setNickName(baseInfoJO.getString("nick_name"));
                                        tbBaseInfo.setName(baseInfoJO.getString("name"));
                                        tbBaseInfo.setGender(baseInfoJO.getString("gender"));
                                        tbBaseInfo.setMobile(baseInfoJO.getString("mobile"));
                                        tbBaseInfo.setRealName(baseInfoJO.getString("real_name"));
                                        tbBaseInfo.setIdentityCode(baseInfoJO.getString("identity_code"));
                                        tbBaseInfo.setVipCount(baseInfoJO.getString("vip_count"));
                                        tbBaseInfo.setUserId(tbLog.getUserId());
                                        tbBaseInfoService.insert(tbBaseInfo);
                                    }
                                    String receiver = taskDataJO.getString("receiver_list");
                                    if (receiver != null){
                                        List<JSONObject> list = JSON.parseArray(receiver,JSONObject.class);
                                        if(list.size()>0){
                                            for(JSONObject j:list){
                                                TbReceiver tbReceiver = new TbReceiver();
                                                tbReceiver.setUserId(tbLog.getUserId());
                                                tbReceiver.setName(j.getString("name"));
                                                tbReceiver.setArea(j.getString("area"));
                                                tbReceiver.setAddress(j.getString("address"));
                                                tbReceiver.setDefaultArea(j.getString("default"));
                                                tbReceiver.setMobile(j.getString("mobile"));
                                                tbReceiver.setTelephone(j.getString("telephone"));
                                                tbReceiver.setZipCode(j.getString("zip_count"));
                                                tbReceiverService.insert(tbReceiver);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //公积金
                if(data.getString("channel_type").equals("GJJ")){
                    JSONObject resultJO = TongdunYYSAuth.gjjGetResult(taskId);
                    if(resultJO.getInteger("code").equals(0)){
                        JSONObject dataJO = resultJO.getJSONObject("data");
                        JSONObject taskData = dataJO.getJSONObject("task_data");
                        //存储baseInfo
                        String baseInfos = taskData.getString("base_info");
                        JSONObject baseInfo = JSON.parseObject(baseInfos);

                        TdGjjBaseInfo tdGjjBaseInfo = new TdGjjBaseInfo();
                        tdGjjBaseInfo.setUserId(Long.valueOf(passback_params));
                        tdGjjBaseInfo.setTaskId(taskId);
                        tdGjjBaseInfo.setCustNo(baseInfo.getString("cust_no"));
                        tdGjjBaseInfo.setPayStatus(baseInfo.getString("pay_status"));
                        tdGjjBaseInfo.setPayStatusDesc(baseInfo.getString("pay_status_desc"));
                        tdGjjBaseInfo.setName(baseInfo.getString("name"));
                        tdGjjBaseInfo.setCertNo(baseInfo.getString("cert_no"));
                        tdGjjBaseInfo.setCertType(baseInfo.getString("cert_type"));
                        tdGjjBaseInfo.setHomeAddress(baseInfo.getString("home_address"));
                        tdGjjBaseInfo.setPostNo(baseInfo.getString("post_no"));
                        tdGjjBaseInfo.setMobile(baseInfo.getString("mobile"));
                        tdGjjBaseInfo.setEmail(baseInfo.getString("email"));
                        tdGjjBaseInfo.setCorpName(baseInfo.getString("corp_name"));
                        tdGjjBaseInfo.setMonthlyCorpIncome(baseInfo.getString("monthly_corp_income"));
                        tdGjjBaseInfo.setMonthlyCorpProportion(baseInfo.getString("monthly_corp_proportion"));
                        tdGjjBaseInfo.setMonthlyCustIncome(baseInfo.getString("monthly_cust_income"));
                        tdGjjBaseInfo.setMonthlyCustProportion(baseInfo.getString("monthly_cust_proportion"));
                        tdGjjBaseInfo.setMonthlyTotalIncome(baseInfo.getString("monthly_total_income"));
                        tdGjjBaseInfo.setBaseNumber(baseInfo.getString("base_number"));
                        tdGjjBaseInfo.setBalance(baseInfo.getString("balance"));
                        tdGjjBaseInfo.setLastPayDate(baseInfo.getString("last_pay_date"));
                        tdGjjBaseInfo.setBeginDate(baseInfo.getString("begin_date"));
                        tdGjjBaseInfo.setCorpNo(baseInfo.getString("corp_no"));
                        tdGjjBaseInfo.setEducation(baseInfo.getString("education"));
                        tdGjjBaseInfo.setRegisted(baseInfo.getString("registed"));
                        tdGjjBaseInfo.setNameOfSpouse(baseInfo.getString("name_of_spouse"));
                        tdGjjBaseInfo.setCertNoOfSpouse(baseInfo.getString("cert_no_of_spouse"));
                        tdGjjBaseInfo.setMaritalStatus(baseInfo.getString("marital_status"));
                        tdGjjBaseInfoService.insert(tdGjjBaseInfo);
                        //payInfo
                        String payInfo = taskData.getString("pay_info");
                        List<String> payInfoStr = JSON.parseArray(payInfo,String.class);
                        if(payInfoStr != null){
                            for(String p : payInfoStr){
                                JSONObject pJO = JSON.parseObject(p);
                                TdGjjPayInfo tdGjjPayInfo = new TdGjjPayInfo();
                                tdGjjPayInfo.setUserId(Long.valueOf(passback_params));
                                tdGjjPayInfo.setTaskId(taskId);
                                tdGjjPayInfo.setGjjNo(pJO.getString("gjj_no"));
                                tdGjjPayInfo.setCorpNo(pJO.getString("corp_no"));
                                tdGjjPayInfo.setCorpName(pJO.getString("corp_name"));
                                tdGjjPayInfo.setBalance(pJO.getString("balance"));
                                tdGjjPayInfo.setPayStatus(pJO.getString("pay_status"));
                                tdGjjPayInfo.setPayStatusDesc(pJO.getString("pay_status_desc"));
                                tdGjjPayInfoService.insert(tdGjjPayInfo);
                            }
                        }
                        //billrecord
                        String billRecord = taskData.getString("bill_record");
                        List<String> billRecordStr = JSON.parseArray(billRecord,String.class);
                        if(billRecordStr != null){
                            for(String b : billRecordStr){
                                JSONObject bJO = JSON.parseObject(b);
                                TdGjjBillRecord tdGjjBillRecord = new TdGjjBillRecord();
                                tdGjjBillRecord.setUserId(Long.valueOf(passback_params));
                                tdGjjBillRecord.setTaskId(taskId);
                                tdGjjBillRecord.setDealTime(bJO.getString("deal_time"));
                                tdGjjBillRecord.setCorpName(bJO.getString("corp_name"));
                                tdGjjBillRecord.setCorpIncome(bJO.getString("corp_income"));
                                tdGjjBillRecord.setCustIncome(bJO.getString("cust_income"));
                                tdGjjBillRecord.setIncome(bJO.getString("income"));
                                tdGjjBillRecord.setOutcome(bJO.getString("outcome"));
                                tdGjjBillRecord.setDesc(bJO.getString("desc"));
                                tdGjjBillRecord.setBalance(bJO.getString("balance"));
                                tdGjjBillRecordService.insert(tdGjjBillRecord);
                            }
                        }
                        //更新状态
                        EntityWrapper<UserAuth> ew = new EntityWrapper<>();
                        ew.eq("user_id",passback_params);
                        UserAuth userAuth = userAuthService.selectOne(ew);
                        userAuth.setGongjijinAuth(1);
                        userAuthService.updateById(userAuth);
                    }
                    return;
                }
                //运营商
                if(data.getString("channel_type").equals("YYS")){
                    JSONObject resultJO = TongdunYYSAuth.getAll(taskId);
                    EntityWrapper ew = new EntityWrapper();
                    ew.eq("task_id", taskId);
                    YYSLog yysLog = yysLogService.selectOne(ew);
                    if (resultJO != null) {
                        JSONObject data1 = resultJO.getJSONObject("data");
                        JSONObject taskData = data1.getJSONObject("task_data");
                        if (taskData != null) {
                            String callInfo = taskData.getString("call_info");
                            List<String> ciList = JSON.parseArray(callInfo, String.class);
                            for (String a : ciList) {
                                List<UserPhoneRecord> userPhoneRecords = new ArrayList<>();
                                String callRecord = JSON.parseObject(a).getString("call_record");
                                List<String> callList = JSON.parseArray(callRecord, String.class);
                                for (String b : callList) {
                                    JSONObject cMap = JSON.parseObject(b);
                                    UserPhoneRecord userPhoneRecord = new UserPhoneRecord();
                                    userPhoneRecord.setStartTime(cMap.getString("call_start_time"));
                                    userPhoneRecord.setCommPlac(cMap.getString("call_address"));
                                    userPhoneRecord.setCallType(cMap.getString("call_type_name"));
                                    userPhoneRecord.setPhoneNo(cMap.getString("call_other_number"));
                                    userPhoneRecord.setConnTimes(cMap.getString("call_time"));
                                    userPhoneRecord.setCommMode(cMap.getString("call_land_type"));
                                    userPhoneRecord.setCommFee(cMap.getString("call_cost"));
                                    userPhoneRecord.setUserId(yysLog.getUserId());
                                    userPhoneRecords.add(userPhoneRecord);
                                }
                                userPhoneRecordService.saveCall(userPhoneRecords);
                            }

                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
